import { Card, message, Row, Col, Space, Divider } from 'antd';
import { history, useRequest } from 'umi';
import ProForm, {
  ProFormDependency,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-form';
import type { FC } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { fakeSubmitForm, queryExperienceDetail, updateExperience } from './servic';
import { queryUserVisitors, queryDiseaseTags, queryCaseVisit } from '@/services/ant-design-pro/api';

const BasicForm: FC<Record<string, any>> = () => {
  const { run } = useRequest(fakeSubmitForm, {
    manual: true,
    onSuccess: () => {
      message.success('提交成功');
    },
  });

  // const { data, loading } = useRequest(() => {
  //   if (history.location.query.id) {
  //     return queryExperienceDetail(history.location.query);
  //   }
  // });

  const onFinish = async (values: Record<string, any>) => {
    console.log('values.diseaseTags', values.diseaseTags);
    let diseaseTags = [];
    for (var i = 0; i < values.diseaseTags.length; i++) {
      let item = {};
      item.diseaseId = values.diseaseTags[i].value;
      item.diseaseName = values.diseaseTags[i].label;
      diseaseTags.push(item);
    }
    values.diseaseTags = diseaseTags;
    let arr = values.user.split('-');
    values.userId = arr[0];
    values.userName = arr[1];
    if (history.location.query.id) {
      values.id = history.location.query.id;
      try {
        const response = await updateExperience(values);
        if (response.code == 200) {
          message.success('修改成功');
        } else {
          message.error('修改失败!');
        }
      } catch (error) {
        console.log(error);
      }
    } else {
      run(values);
    }
  };

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  return (
    <PageContainer content="">
      <Card bordered={false}>
        <ProForm
          hideRequiredMark
          style={{ margin: 'auto', marginTop: 8 }}
          name="basic"
          layout="horizontal"
          // initialValues={data}
          onFinish={onFinish}
          {...formItemLayout}
          request={async () => {
            if (history.location.query.id) {
              return queryExperienceDetail(history.location.query).then(({ data }) => {
                let diseaseTags = [];
                for (var i = 0; i < data.diseaseTags.length; i++) {
                  let item = {};
                  item.value = data.diseaseTags[i].diseaseId;
                  item.label = data.diseaseTags[i].diseaseName;
                  item.key = i;
                  diseaseTags.push(item);
                }
                data.diseaseTags = diseaseTags;
                data.addUserType = data.addUserType + '';
                data.user = data.userId + '-' + data.userName;
                console.log('data', data);
                return data;
              });
            } else {
              return {};
            }
          }}
          submitter={{
            render: (props, doms) => {
              return (
                <Row>
                  <Col span={14} offset={4}>
                    <Space>{doms}</Space>
                  </Col>
                </Row>
              );
            },
          }}
        >
          <ProFormSelect
            width="md"
            name="user"
            label="就诊人"
            request={async ({ keyWords }) => {
              let query = {
                likeQuery: {
                  visitorName: keyWords,
                },
                pageNum: 1,
                pageSize: 20,
              };
              return queryUserVisitors(query).then(({ data }) => {
                return data.records.map((item) => {
                  let sex = item.sex == 1 ? '男' : '女';
                  return {
                    label: item.visitorName + '  ' + sex + '  ' + item.birthday,
                    value: item.id + '-' + item.visitorName,
                  };
                });
              });
            }}
          />
          <ProFormDependency name={['user']}>
            {({ user }) => {
              console.log('user', user);
              return (
                <ProFormSelect
                  params={{
                    key: user,
                  }}
                  width="md"
                  name="userCaseId"
                  label="就诊病历"
                  request={async () => {
                    let arr = user.split('-');
                    return queryCaseVisit({ visitorId: arr[0] }).then(({ data }) => {
                      return data.map((item) => {
                        return {
                          label:
                            item.visitorName + '  ' + item.diseaseName + '  ' + item.confirmedTime,
                          value: item.id,
                        };
                      });
                    });
                  }}
                />
              );
            }}
          </ProFormDependency>
          <Divider />
          <ProFormText
            width="md"
            label="经验文章"
            name="articleId"
            rules={[
              {
                required: true,
                message: '请输入经验文章',
              },
            ]}
            placeholder="请输入经验文章ID"
          />
          <ProFormSelect
            width="md"
            name="diseaseTags"
            label="疾病标签"
            showSearch
            fieldProps={{
              labelInValue: true,
              mode: 'multiple',
            }}
            request={async () => {
              return queryDiseaseTags().then(({ data }) => {
                return data.map((item) => {
                  return {
                    label: item.name,
                    value: item.id,
                  };
                });
              });
            }}
          />
          <ProFormRadio.Group
            options={[
              {
                value: '0',
                label: '用户',
              },
              // {
              //   value: '1',
              //   label: '医生',
              // },
              // {
              //   value: '2',
              //   label: '系统',
              // },
            ]}
            label="记录添加人"
            name="addUserType"
          />
          <ProFormText
            width="md"
            name="addUserId"
            label=" "
            rules={[
              {
                required: true,
                message: '请输入用户id',
              },
            ]}
            fieldProps={{
              style: {
                margin: '8px 0',
              },
            }}
            placeholder="请输入用户id"
          />
        </ProForm>
      </Card>
    </PageContainer>
  );
};

export default BasicForm;
